<template>
  <div class="container">
    <a-divider orientation="left" orientation-margin="0px">工具箱水印任务</a-divider>
    <!--数据水印-->
    <a-row class="toolbox-left">
      <a-col :span="24" v-if="toolboxcom">
        <a-form :model="formState" name="validate_other" v-bind="formItemLayout" @finish-failed="onFinishFailed" @finish="onFinish" :rules="formRules">
          <a-form-item style="font-size: 24px">
            <a-form-item name="dragger" noStyle>
              <a-upload-dragger
                v-model:fileList="fileList"
                name="file"
                :multiple="false"
                :action="originalAction"
                :beforeUpload="beforeUpload"
                :data="(file) => ({ fileName: file.name, fileSize: file.size })"
                :headers="uploadHeaders"
                @change="handleChange"
                @drop="handleDrop"
              >
                <p class="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p class="ant-upload-text">点击或将文件拖拽到这里上传</p>
                <p class="ant-upload-hint" style="padding: 10px 14px 0">
                  支持对以下文件类型添加水印：DMP、TXT、CSV、XLSX、XLS、DEL、DOC、DOCX、PPT、PPTX、PDF、DCM、PNG、JPG、JPEG、BMP、E，及含上述格式的 ZIP/TAR/TAR.GZ 压缩包。
                </p>
              </a-upload-dragger>
            </a-form-item>
          </a-form-item>
          <a-divider orientation="left" orientation-margin="0px">添加水印内容</a-divider>
          <a-form-item name="group">
            <a-input v-model:value="formState.group" />
          </a-form-item>
          <a-form-item style="text-align: center">
            <a-button type="primary" htmlType="submit" size="large" :disabled="isSubmitting">添加水印</a-button>
          </a-form-item>
        </a-form>
      </a-col>

      <a-col :span="24" class="toolboxbut" v-if="toolboxbut">
        <!--正在处理文件-->
        <a-space v-if="loading" class="loading">
          <a-spin tip="文件正在处理中..." size="large" />
        </a-space>

        <!--开始下载-->

        <a-result status="success" title="文件添加水印成功" :subTitle="subTitle" v-if="dowbut">
          <template #extra>
            <a-button type="primary" size="large" @click="postDownload">
              <template #icon>
                <DownloadOutlined />
              </template>
              安全下载
            </a-button>
          </template>
        </a-result>
      </a-col>
      <a-col :span="24" class="toolboxend" v-if="toolboxend">
        <a-button size="large" @click="goToToolbox">返回工具箱</a-button>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="24" class="zi_bottom">
        <p>工具对上传的文件添加自定义不可见水印信息，保障文件供给可溯源，使用步骤如下：</p>
        <p>（1）上传文件</p>
        <p>（2）输入自定义水印信息</p>
        <p>（3）点击 【添加水印】启动处理​</p>
        <p>（4）处理完成后，点击【下载】将已添加水印的文件下载至本地​</p>
      </a-col>
    </a-row>
  </div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue'
import { UploadOutlined, InboxOutlined, DownloadOutlined, BookFilled } from '@ant-design/icons-vue'
import type { UploadChangeParam, UploadFile } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { useUserStoreWithOut } from '@/stores/modules/user'
import { dmsMaskCenterApi } from '@/api/dms-mask-center'
import { GetDownloadList } from '@/api/dms-mask-center/type'
import { http } from '@/utils/http'
import type { ApiResult } from '@/types/app'
import { useRouter } from 'vue-router'
const fileList = ref<UploadFile[]>([])
const subTitle = ref('')
const namekey = ref('')
const wataskid = ref('')
const loading = ref(false)
const dowbut = ref(false)
const isSubmitting = ref(false)
const absPath = ref('')
const toolboxcom = ref(true)
const toolboxbut = ref(false)
const toolboxend = ref(false)

const formRules = {
  // 文件上传校验：必须上传文件
  file: [
    {
      required: true,
      message: '请上传文件',
      trigger: ['change', 'submit']
    }
  ],
  // 水印内容校验：不能为空
  group: [
    {
      required: true,
      message: '请输入水印内容',
      trigger: ['blur', 'change'] // 失去焦点或输入变化时校验
    },
    {
      min: 1,
      message: '水印内容不能为空',
      trigger: ['blur', 'change']
    }
  ]
}
const originalAction = import.meta.env.VITE_GLOB_API_URL + 'dms-mask-center/api/v1/resource/uploadOssFile'

const handleChange = (info: UploadChangeParam) => {
  const status = info.file.status
  if (status === 'done') {
    message.success(`文件上传成功！`)
    const response = info.file.response
    subTitle.value = info.file.name

    // console.log('后端返回内容：', response);
    namekey.value = response.data.key
    absPath.value = response.data.absPath
  } else if (status === 'error') {
    message.error(`文件上传失败！`)
  }
}
const beforeUpload = (file: UploadFile) => {
  // 检查当前文件列表长度，若已有文件则阻止上传
  if (fileList.value.length >= 1) {
    message.warning('只能上传一个文件，请先删除已上传的文件！')
    return false // 阻止上传
  }
  return true
}
function handleDrop(e: DragEvent) {
  console.log(e)
}
//请求头内容
const uploadHeaders = {
  Authorization: `Bearer ${useUserStoreWithOut().getToken()}` // 示例：添加身份令牌
}
const formState = reactive<Record<string, any>>({
  group: '' // 必须添加，与输入框绑定对应
})
//提交执行
const onFinish = (values: any) => {
  if (fileList.value.length <= 0) {
    message.error('请上传需要加水印的文件！')
    return false
  }
  //按钮禁用
  isSubmitting.value = true

  // 获取各时间部分并补零
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0') // 月份从0开始，需+1
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const formattedTime = `${year}${month}${day}${hours}${minutes}`

  dmsMaskCenterApi
    .postWatermark({
      data: {
        name: '工具箱水印任务' + formattedTime,
        type: 'WATERMARK',
        mode: 'FILE_TO_FILE',
        classifyIds: null,
        sourceResourceId: import.meta.env.VITE_GLOB_SRID,
        cycleType: 'IMMEDIATE',
        watermarkRuleId: '1',
        ticketNumber: formattedTime,
        provideDataParty: '1',
        useDataParty: '1',
        watermarkContent: 'CUSTOMIZE',
        noResSourceWaterMarkFileFlag: false,
        noResTargetWaterMarkFileFlag: false,
        sourceFilePathSelect: [
          {
            absPath: absPath.value
          }
        ],
        fileSelect: [
          {
            fileNameKey: namekey.value,
            fileName: subTitle.value,
            absPath: absPath.value
          }
        ],
        watermarkType: 'pseudo_column_embedding',
        watermarkContentType: 'CUSTOMIZE',
        watermarkCustomizeContent: values.group,
        fileEncoding: 'UTF-8',
        autoMaskFlag: 'NO',
        dataType: 'offline'
      }
    })
    .then((response) => {
      loading.value = false
      dowbut.value = false
      loading.value = true
      toolboxcom.value = false
      toolboxbut.value = true
      toolboxend.value = true
      // console.log(response.data.id);
      http.put<ApiResult<any>>({ url: '/dms-mask-center/api/v1/task/submit/' + response.data.id })
      wataskid.value = response.data.id
      setTimeout(function () {
        loading.value = false
        dowbut.value = true
        isSubmitting.value = false
      }, 15000)
    })
    .catch((error) => {
      // message.warning('提交失败！');
      isSubmitting.value = false
    })

  console.log('Success:', values)
}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo)
}
//下载文件
const postDownload = async (record: any) => {
  dmsMaskCenterApi
    .getDownloadList()
    .then((response) => {
      const dataList = response.data || []
      const matchedItem = dataList.find((item) => item.taskId === wataskid.value)
      window.open('https://' + window.location.host + '/dms-mask-center/api/v1/dataoffline/task/downloadRecord/watermark-file?id=' + matchedItem.id + '&taskId=' + wataskid.value)
    })
    .catch((error) => {
      message.warning('文件加水印失败请重新尝试！')
    })
}
//提交加水印
const postwatermark = () => {}

const router = useRouter()
const goToToolbox = () => {
  // 使用 router.push 跳转到指定路由
  location.reload()
}
</script>

<style scoped>
.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
.form-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}
.ant-form-item .ant-form-item-label > label {
  font-size: 16px;
}
:where(.css-dev-only-do-not-override-10npqub).ant-upload-wrapper .ant-upload-drag p.ant-upload-drag-icon .anticon {
  font-size: 7rem;
}
:where(.css-dev-only-do-not-override-10npqub).ant-upload-wrapper .ant-upload-drag p.ant-upload-text {
  color: #1890ff;
}
.container .zi_bottom {
  border-top: solid 10px #eef4ff;
  padding: 1rem 0;
}
.ant-result .ant-result-title {
  color: #1890ff;
  font-size: 18px;
}
.ant-result {
  padding-top: 11vh;
}
.container .toolboxbut {
  border: 1px dashed #d9d9d9;
  text-align: center;
  min-height: 42vh;
}
.container .toolboxbut .loading {
  padding-top: 20vh;
}
.container .toolboxend {
  text-align: center;
  margin: 28px 0;
}
.ant-result .ant-result-extra {
  margin-top: 12px;
}
.zi_bottom h1 {
  font-size: 16px;
}
.zi_bottom p {
  color: #999;
}
</style>
